import tkinter as tk
import math
from tkinter import messagebox

class Calculator(tk.Tk):
    def __init__(self):
        super().__init__()
        self.title("TianQi AI 计算器")
        self.geometry("400x600")
        self.resizable(False, False)
        self.configure(bg="#F0F0F0")
        
        # 初始化变量
        self.current_input = tk.StringVar()
        self.current_input.set("0")
        self.formula = ""
        self.create_widgets()
        
    def create_widgets(self):
        # 显示区域
        display_frame = tk.Frame(self, bg="#F0F0F0")
        display_frame.pack(padx=20, pady=20, fill=tk.BOTH, expand=True)
        
        # 输入显示框
        display = tk.Entry(display_frame, textvariable=self.current_input, font=("Arial", 36), 
                          borderwidth=0, bg="#F0F0F0", fg="#333333", justify="right", 
                          readonlybackground="#F0F0F0", state="readonly")
        display.pack(fill=tk.BOTH, expand=True)
        
        # 按钮区域
        button_frame = tk.Frame(self, bg="#F0F0F0")
        button_frame.pack(padx=20, pady=10, fill=tk.BOTH, expand=True)
        
        # 按钮布局和文本
        buttons = [
            ('%', '√', 'C', '⌫'),
            ('1/x', 'x²', '7', '8', '9', '/'),
            ('(', ')', '4', '5', '6', '*'),
            ('π', 'e', '1', '2', '3', '-'),
            ('±', '0', '.', '=', '+')
        ]
        
        self.button_objs = []
        
        # 创建按钮
        for row_idx, row in enumerate(buttons):
            button_row = []
            for col_idx, char in enumerate(row):
                btn = tk.Button(
                    button_frame, text=char, font=("Arial", 18),
                    command=lambda c=char: self.on_button_click(c),
                    relief="flat", bg=self.get_button_color(char),
                    fg=self.get_text_color(char), height=1, width=3
                )
                btn.grid(row=row_idx, column=col_idx, padx=5, pady=5, sticky="nsew")
                button_row.append(btn)
                
                # 调整特殊按钮大小
                if char == '=':
                    btn.config(width=7)
                
                # 设置网格列权重
                button_frame.columnconfigure(col_idx, weight=1)
            self.button_objs.append(button_row)
            button_frame.rowconfigure(row_idx, weight=1)
    
    def get_button_color(self, char):
        """根据按钮类型返回不同的背景颜色"""
        if char in {'C', '⌫'}:
            return "#FF9999"  # 红色
        elif char in {'+', '-', '*', '/', '='}:
            return "#A0D8EF"  # 蓝色
        elif char in {'√', '1/x', 'x²', '%', '±', 'π', 'e'}:
            return "#C2F0C2"  # 绿色
        else:
            return "#FFFFFF"  # 白色
    
    def get_text_color(self, char):
        """根据按钮类型返回不同的文本颜色"""
        if char in {'C', '⌫'}:
            return "#FFFFFF"  # 白色
        elif char in {'+', '-', '*', '/', '=', '√', '1/x', 'x²', '%', '±', 'π', 'e'}:
            return "#000000"  # 黑色
        else:
            return "#333333"  # 深灰
    
    def on_button_click(self, char):
        """处理按钮点击事件"""
        current = self.current_input.get()
        
        # 处理特殊功能按钮
        if char == 'C':  # 清除
            self.current_input.set("0")
            self.formula = ""
        
        elif char == '⌫':  # 退格
            if current != "0" and len(current) > 1:
                self.current_input.set(current[:-1])
            else:
                self.current_input.set("0")
        
        elif char == '=':  # 计算结果
            try:
                # 添加当前输入到公式
                if current != "0":
                    self.formula += current
                
                # 替换特殊符号进行计算
                expression = self.formula.replace('π', str(math.pi))
                expression = expression.replace('e', str(math.e))
                expression = expression.replace('√', 'math.sqrt')
                expression = expression.replace('x²', '**2')
                
                # 计算表达式
                result = eval(expression)
                self.current_input.set(str(result))
                self.formula = ""
            except Exception as e:
                messagebox.showerror("错误", "无效的表达式")
                self.current_input.set("0")
                self.formula = ""
        
        elif char == '±':  # 正负号
            if current != "0":
                if current.startswith('-'):
                    self.current_input.set(current[1:])
                else:
                    self.current_input.set('-' + current)
        
        elif char == '√':  # 平方根
            try:
                self.formula += char
                self.current_input.set("0")
            except:
                messagebox.showerror("错误", "无法计算平方根")
        
        elif char in {'+', '-', '*', '/'}:  # 运算符
            # 将当前输入加入公式并重置当前输入
            self.formula += current
            self.formula += char
            self.current_input.set("0")
        
        elif char == '1/x':  # 倒数
            try:
                value = eval(current)
                self.current_input.set(str(1/value))
            except:
                messagebox.showerror("错误", "无法计算倒数")
        
        elif char == 'x²':  # 平方
            try:
                value = eval(current)
                self.current_input.set(str(value ** 2))
            except:
                messagebox.showerror("错误", "无法计算平方")
        
        elif char == '%':  # 百分比
            try:
                value = eval(current)
                self.current_input.set(str(value / 100))
            except:
                messagebox.showerror("错误", "无法计算百分比")
        
        elif char in {'π', 'e'}:  # 常量
            # 加入公式并显示在输入框
            self.formula += char
            self.current_input.set(char)
        
        else:  # 数字和小数点
            if current == "0":
                if char == '.':
                    self.current_input.set("0.")
                else:
                    self.current_input.set(char)
            else:
                # 防止多个小数点
                if char == '.' and '.' in current:
                    return
                self.current_input.set(current + char)

if __name__ == "__main__":
    app = Calculator()
    app.mainloop()